package ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;
import service.IBookService;
import service.ICartLineService;
import service.ICartService;
import service.Impl.IBookServiceImpl;
import service.Impl.ICartLineServiceImpl;
import service.Impl.ICartServiceImpl;
import vo.Book;
import vo.Cart;
import vo.CartLine;
import vo.Client;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/*
* @description: 添加购物车，实现用户点击商品添加到购物车功能
* 从前端接收：bookId ，页数信息1   从session获得：userId
* 传给前端：cartLines(list<CartLine>)   cart(cart)
*/
@WebServlet(name = "CartLineAddServlet")
public class CartLineAddServlet extends HttpServlet {
    private ICartService cartService = new ICartServiceImpl();
    private IBookService bookService = new IBookServiceImpl();
    /*
    * @description:从前端获取的数据有bookId,以及当前会话（userId）
    * @param [req, resp]
    * @return void
    */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取输入流
        ServletInputStream inputStream = req.getInputStream();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder=new StringBuilder();
        String temp="";
        while((temp=bufferedReader.readLine())!=null){
            stringBuilder.append(temp);
        }
        //处理成json对象
        String jsonString=stringBuilder.toString();
        JSONObject jsonObject=JSON.parseObject(jsonString);
        //解析json对象
        int bookId=Integer.parseInt(jsonObject.getString("bookId"));
        //获得当前用户
        HttpSession httpSession=req.getSession();
        Client client=(Client) httpSession.getAttribute("client");
        if(client!=null){
            int userId=client.getId();

            //具体业务逻辑  并调用service层获得返回CartLine9对象
            ICartLineServiceImpl cartLineService=new ICartLineServiceImpl();
            boolean result=cartLineService.addCartLine(userId,bookId);



            if(!result){
                //库存不足无法添加
            }
            else {
                //更新session数据中的cartLine和cart
                Cart cart= cartService.selectCart(client.getId());
                List<CartLine> cartLineList = cartLineService.selectCartLineByCartId(cart.getId());
                List<Book> bookList = new ArrayList<>();
                for(CartLine cartLine : cartLineList){
                    bookList.add(bookService.selectBookById(cartLine.getBookId()));
                }
                httpSession.setAttribute("cart", cart);
                httpSession.setAttribute("cartLines", cartLineList);
                httpSession.setAttribute("books", bookList);

                IBookService bookService = new IBookServiceImpl();
                Book book = bookService.selectBookById(bookId);
                String bookJson = JSONObject.toJSONString(book);
                resp.getWriter().write(bookJson);
            }
        }else{
            resp.getWriter().write("{\"status\":102}");
        }



    }
}
